<template>
  <div class="todoapp">
    <!-- 头 -->
    <todo-header :list="list" @add="add"></todo-header>
    <!-- 身体 -->
    <todo-main :list="selectList" @del="del"></todo-main>
    <!-- 底部 -->
    <!-- $event在原生标签里是事件对象，在组件里是组件传递过来的数据 -->
    <!-- 要删除已完成，其实就是过滤出所有未完成的数据 -->
    <todo-footer
      :list="selectList"
      @change="status = $event"
      @clear="list = list.filter(v => !v.isDone)"
    ></todo-footer>
  </div>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter
  },
  data () {
    return {
      status: '全部',
      list: JSON.parse(localStorage.getItem('todos99')) || [
        { id: 100, name: '吃饭', isDone: true },
        { id: 201, name: '睡觉', isDone: false },
        { id: 103, name: '打豆豆', isDone: true }
      ]
    }
  },
  methods: {
    del (id) {
      // 删除相当于就是把被删元素以外的元素筛选出来
      this.list = this.list.filter(v => v.id !== id)
    },

    add (task) {
      // 添加到数组
      this.list.push({
        id: Date.now(),
        name: task,
        isDone: false
      })
    }
  },

  computed: {
    selectList () {
      // 根据不同的status返回不同的数组
      if (this.status === '已完成') {
        // 筛选出已完成并返回
        return this.list.filter(v => {
          return v.isDone === true
        })
      } else if (this.status === '未完成') {
        // return this.list.filter(v => !v.isDone)
        return this.list.filter(v => {
          return v.isDone === false
        })
      } else {
        // 全部
        return this.list
      }
    }
  },
  watch: {
    list: {
      deep: true,
      handler () {
        localStorage.setItem('todos99', JSON.stringify(this.list))
      }
    }
  }
}
</script>

<style></style>
